/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.io.DataOutput;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Income;
import com.jeeplus.modules.ap.entity.Yue;
import com.jeeplus.modules.ap.service.YueService;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.infor.entity.Department;
import com.jeeplus.modules.infor.entity.Position;
import com.jeeplus.modules.infor.entity.Staff;
import com.jeeplus.modules.infor.service.DepartmentService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.entity.Import;
import com.jeeplus.modules.wms.entity.Outbound;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Imprest;
import com.jeeplus.modules.ap.service.ImprestService;

/**
 * 备用金Controller
 * @author slD
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/imprest")
public class ImprestController extends BaseController {

	@Autowired
	private ImprestService imprestService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private YueService yueService;
	@ModelAttribute
	public Imprest get(@RequestParam(required = false) String id) {
		Imprest entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = imprestService.get(id);
		}
		if (entity == null) {
			entity = new Imprest();
		}
		return entity;
	}

	/**
	 * 备用金列表页面
	 */
	@RequiresPermissions("ap:imprest:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/imprestList";
	}

	/**
	 * 备用金列表页面
	 */
	@RequiresPermissions("ap:imprest:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/2/imprestList";
	}

	/**
	 * 备用金列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:imprest:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Imprest imprest, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			imprest.setProjectName(pro);}
			Page<Imprest> page = imprestService.findPage(new Page<Imprest>(request, response), imprest);
		return getBootstrapData(page);
	}

	/**
	 * 备用金列表数据（报表）
	 */
	@ResponseBody
	@RequiresPermissions("ap:imprest:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Imprest imprest, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			imprest.setProjectName(pro);}
			imprest.setDocumentStatus("已到账确认");
		Page<Imprest> page = imprestService.findPage(new Page<Imprest>(request, response), imprest);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑备用金表单页面
	 */
	@RequiresPermissions(value = {"ap:imprest:view", "ap:imprest:add", "ap:imprest:edit"}, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(Imprest imprest, Model model,String ln) {
		if(ln!=null&&ln!=""){
			model.addAttribute("ln", ln);
		}
		if(imprest.getIsNewRecord()){
			imprest.setDocumentStatus("已创建");
			imprest.setProjectName(UserUtils.getUseroffice());
			Department d=new Department();
			d.setProject(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			d=departmentService.findList(d).get(0);
			d=departmentService.get(d.getId());
			imprest.setApplicationDivision(d.getName());
			imprest.setApplicationDate(new Date());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Imprest i=new Imprest();
			i.setNumber(code);
			List<Imprest> list=imprestService.findList(i);
			if(list==null||list.size()<1){
				imprest.setNumber(code+"001"+"BYJ");
			}else{
				if(list.size()/10==0){
					imprest.setNumber(code+"00"+(list.size()+1)+"BYJ");
				}else
				if(list.size()/100==0){
					imprest.setNumber(code+"0"+(list.size()+1)+"BYJ");
				}else{imprest.setNumber(code+(list.size()+1)+"BYJ");}

			}
			Staff staff =new Staff();
			staff.setProjectName(UserUtils.getUseroffice());
			List<Staff> l=staffService.findList(staff);
			for(Staff s:l){
				if(staffService.get(s.getId()).getPosition().getName().contains("财务")){
					imprest.setApplicant(s.getName());
				}
			}
		}
		model.addAttribute("imprest", imprest);
		return "modules/ap/imprestForm";
	}

	/**
	 * 备用金报表查询
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(String min,String max,String pro){
		Imprest i=new Imprest();
		i.setMinDate(min);
		i.setMax(max);
		i.setDocumentStatus("已到账确认");
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			i.setProjectName(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				i.setProjectName(UserUtils.getUseroffice());
			}
		}
		List<Imprest> list=imprestService.findList(i);
		double xj=0.0;
		double yk=0.0;
		String ids="";
		for(Imprest im:list){
			ids+=im.getId()+",";
			if(im.getMoney().equals("油卡")){
				yk+= Double.parseDouble(im.getPaymentMoney());
			}else{
				xj+= Double.parseDouble(im.getPaymentMoney());
			}
		}
		i.setMoney(yk+"");
		i.setPaymentMoney(xj+"");
		i.setMax(ids);
		list.add(i);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Imprest> list =new ArrayList<Imprest>();
		for(String id:idd){
			list.add(imprestService.get(id));
		}

		Export e=new Export();
		e.exportimprest(response,list);
	}

	/**
	 * 保存备用金
	 */
	@ResponseBody
	@RequiresPermissions(value = {"ap:imprest:add", "ap:imprest:edit"}, logical = Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Imprest imprest,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, imprest)) {
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
        String ln=request.getParameter("ln");
		if(ln!=null&&ln!=""){
			imprest.setDzrq(new Date());
			imprest.setDocumentStatus("已到账填写");
		}
		imprestService.save(imprest);//保存
		j.setSuccess(true);
		j.setMsg("保存备用金成功");
		return j;
	}

	/**
	 * 删除备用金
	 */
	@ResponseBody
	@RequiresPermissions("ap:imprest:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Imprest imprest, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		imprestService.delete(imprest);
		j.setMsg("删除备用金成功");
		return j;
	}

	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Imprest imprest, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		imprest.setDocumentStatus("已确认待审批");
		imprestService.save(imprest);
		j.setMsg("确认成功");
		return j;
	}

	/**
	 * 到账确认
	 */
	@ResponseBody
	@RequestMapping(value = "dzqr")
	public AjaxJson dzqr(Imprest imprest, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		NumberFormat nf = NumberFormat.getInstance();
		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		if(imprest.getMoney().equals("现金")){
			yue.setXj(nf.format(Double.parseDouble(yue.getXj())+Double.parseDouble(imprest.getPaymentMoney())).replaceAll(",",""));
		}else{
			yue.setYk(nf.format(Double.parseDouble(yue.getYk())+Double.parseDouble(imprest.getPaymentMoney())).replaceAll(",",""));

		}
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())+Double.parseDouble(imprest.getPaymentMoney())).replaceAll(",",""));
		yueService.save(yue);
		imprest.setDocumentStatus("已到账确认");
		imprestService.save(imprest);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 删除备用金
	 */
	@ResponseBody
	@RequestMapping(value = "bh")
	public AjaxJson bh(Imprest imprest, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		imprest.setDocumentStatus("审核未通过");
		imprestService.save(imprest);
		j.setMsg("驳回成功");
		return j;
	}

	/**
	 * 批量删除备用金
	 */
	@ResponseBody
	@RequiresPermissions("ap:imprest:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			imprestService.delete(imprestService.get(id));
		}
		j.setMsg("删除备用金成功");
		return j;
	}


	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:imprest:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Imprest imprest, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "备用金" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Imprest> page = imprestService.findPage(new Page<Imprest>(request, response, -1), imprest);
			new ExportExcel("备用金", Imprest.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出备用金记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public Imprest detail(String id) {
		return imprestService.get(id);
	}


	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("ap:imprest:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Imprest> list = ei.getDataList(Imprest.class);
			for (Imprest imprest : list) {
				try {
					imprestService.save(imprest);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条备用金记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条备用金记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入备用金失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ap/imprest/?repage";
	}

	/**
	 * 下载导入备用金数据模板
	 */
	@RequiresPermissions("ap:imprest:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "备用金数据导入模板.xlsx";
			List<Imprest> list = Lists.newArrayList();
			new ExportExcel("备用金数据", Imprest.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ap/imprest/?repage";
	}

	/**
	 * 根据id修改状态
	 *
	 * @return
	 */
	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public String updateStatus(Imprest imprest, HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		if (StringUtils.isNotEmpty(ids)) {
			String[] str = ids.split(",");
			if (str != null && str.length > 0) {
				for (String id : str) {
					if (StringUtils.isNotEmpty(id)) {
						imprest = imprestService.get(id);
						String position=UserUtils.getposition();
						if(position.equals("办事处经理")){
							imprest.setDocumentStatus("经理已审批");
						}
						if(position.contains("总监")){
							imprest.setDocumentStatus("总监已审批");
						}
						imprestService.save(imprest);
					}
				}
			}
		}
		return "success";
	}


	@RequestMapping(value = "status")
	@ResponseBody
	public String status(Imprest imprest, HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		if (StringUtils.isNotEmpty(ids)) {
			String[] str = ids.split(",");
			if (str != null && str.length > 0) {
				for (String id : str) {
					if (StringUtils.isNotEmpty(id)) {
						imprest = imprestService.get(id);
						imprest.setDocumentStatus("3");//修改状态为已到账
						imprestService.save(imprest);
					}


				}
			}


		}


		return "succe";
	}


}